<template>
  <div class="flex flex-col h-full">
    <SearchContainer @search="queryList" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" layout="inline" :model="formState" :label-col="{ style: { width: '75px' } }">
        <a-form-item name="bqid" label="" class="w-36">
          <SelectArea v-model:value="formState.bqid" use-cache set-cache @change="queryList()" />
        </a-form-item>
        <a-form-item name="bedCode" label="">
          <a-input v-model:value="formState.bedCode" class="w-56 ml-2" placeholder="床位号" allow-clear />
        </a-form-item>
        <a-form-item name="zjm" label="">
          <a-input v-model:value="formState.zjm" class="w-56 ml-2" placeholder="姓名/助记码/住院号" allow-clear />
        </a-form-item>
        <a-form-item name="" label="申请日期">
          <a-range-picker v-model:value="formState.dateRange" class="w-56" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2 flex-1">
      <div class="flex items-center justify-end mb-2">
        <a-button type="primary" ghost class="mr-2" @click="onBatchPrintCard">打印巡视卡</a-button>
        <a-button type="primary" ghost @click="onBatchPrintBottle">打印瓶贴</a-button>
      </div>
      <div class="absolute top-[-9999px] hidden">
        <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
        <a-button ref="printMeS" v-print="{ id: 'printMeS' }">打印</a-button>
        <PrintView id="printMe" :print-data="printData" />
        <PrintViewS id="printMeS" :print-data="printData" />
      </div>
      <BaseTable
        :loading="loading"
        :data-source="tableData"
        :scroll="{ x: 1800 }"
        fill
        row-key="id"
        column-code="00001009"
        :row-selection="{ selectedRowKeys, getCheckboxProps: (row) => ({ disabled: row.isChild }), onChange: onSelectChange }"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            <span>{{ index + 1 }}</span>
          </template>
          <template v-if="column.dataIndex === 'systatus'">
            <a-tag v-if="record.systatus" color="blue">{{ record.systatus }}</a-tag>
            <span v-else>-</span>
          </template>
          <template v-if="column.dataIndex === 'brxxbEntity'"><NameItem :resource-data="record.brxxbEntity" /></template>
          <div v-if="column.dataIndex === 'children'">
            <DoctorAdviceOrder
              :row-data="record"
              :params-key="{ mc: 'adv.mc', gg: 'adv.gg', sl: 'clinicalDose', dw: 'clinicalDoseUnit', yf: 'deliverRoute.fyff', pl: 'fqy.plid' }"
            />
          </div>
          <!-- 医嘱状态 已申请,已发药，已执行，已撤销 -->
          <template v-if="column.dataIndex === 'action'">
            <a-button v-if="record.systatus == '已申请'" type="link" size="small" @click="onExecute([record.id], 1)">执行</a-button>

            <a-button type="link" size="small" @click="onPrintBottle(record)">瓶贴</a-button>
            <a-button type="link" size="small" @click="onPrintCard(record)">巡视卡</a-button>
            <BaseButton v-if="record.systatus == '已申请'" confirm-text="确定撤销申请吗？" type="link" size="small" danger @click="onCancelApply(record.id)">
              撤销申请
            </BaseButton>
            <BaseButton v-if="record.systatus == '已执行'" confirm-text="确定撤销执行吗？" type="link" size="small" danger @click="onExecute([record.id], 2)">
              撤销执行
            </BaseButton>
          </template>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'
import SelectArea from '@/components/SelectArea'
import { getSystemConfig } from '@/utils/systemConfig'
import NameItem from '../components/NameItem'
import PrintView from './PrintView.vue'
import PrintViewS from './PrintViewS.vue'

const loading = ref(false)
const tableData = ref([])
const formRef = ref(null)
const printData = ref({})
const printMe = ref()
const printMeS = ref()
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})

const queryList = async () => {
  loading.value = true
  const { code, data } = await post('/inp/clinicalOrder/getClinicalOrderList', {
    bqid: formState.value.bqid,
    zjm: formState.value.zjm,
    bedCode: formState.value.bedCode,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    sfsyyz: 1
  })
  if (code !== 0) return
  tableData.value = data.map((item) => {
    return {
      ...item,
      children: item.children?.map((child) => ({
        ...child,
        isChild: true
      }))
    }
  })
  loading.value = false
}
//撤销申请
const onCancelApply = async (id) => {
  const { code, msg } = await post('/inp/clinicalOrder/doCancelApplyClinicalOrder', {
    id
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success(msg)
  queryList()
}
//执行/撤销执行
const onExecute = async (ids, execStatus) => {
  const { code, msg } = await post('/inp/clinicalOrder/doNurseExecuteClinicalOrder', {
    zxyzids: ids,
    execStatus,
    execNurseStatus: execStatus === 1 ? execStatus : 0
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success(msg)
  queryList()
}

// 瓶贴
const onPrintBottle = async (row) => {
  if (!row?.fqy?.sl) return message.error('输液瓶贴数量为0')
  for (let i = 0; i < row?.fqy?.sl; i++) {
    const { code, msg, data } = await post('/inp/Print/printInpInfusionBottleStickers', {
      advId: row?.inpAdviceid,
      children: row?.children,
      dqsy: i + 1,
      zs: row?.fqy?.sl || 0,
      stdate: row.execTime ? dayjs(row.execTime).format('YYYY-MM-DD') : '',
      eddate: row.execTime ? dayjs(row.execTime).format('YYYY-MM-DD') : ''
    })
    if (code !== 0) return message.error(msg)
    if (getSystemConfig('NAVYHIS_MODE') === '1') {
      printData.value = JSON.parse(data)
      setTimeout(() => {
        printMeS.value.$el.click()
      }, 100)
    } else {
      window.openExe?.rpt(data) //调用winform打印
    }
  }
}

// 巡视卡打印
const onPrintCard = async (row) => {
  const { code, msg, data } = await post('/inp/Print/printIntravenousInfusionPatrolCard', {
    advId: row?.inpAdviceid,
    inplsh: row?.inplsh,
    stdate: row.execTime ? dayjs(row.execTime).format('YYYY-MM-DD') : '',
    eddate: row.execTime ? dayjs(row.execTime).format('YYYY-MM-DD') : ''
  })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      setPrintSize('A5', 'landscape')
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
const selectedRowKeys = ref([])
const onSelectChange = (keys) => {
  selectedRowKeys.value = keys
}
const onBatchPrintCard = async () => {
  const { code, msg, data } = await post('inp/Print/printAllIntravenousInfusionPatrolCard', {
    ids: selectedRowKeys.value,
    ...formState.value,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1]
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const onBatchPrintBottle = async () => {
  const { code, msg, data } = await post('inp/Print/printALlInpInfusionBottleStickers', {
    ids: selectedRowKeys.value,
    ...formState.value,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1]
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
onMounted(() => {
  queryList()
})
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
